package com.thlws.study.rabbitmq.internal.receiver;

import com.rabbitmq.client.Channel;
import com.thlws.study.rabbitmq.internal.RmqConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Direct模式
 * @author HanleyTang 2019-06-23
 */
@Component
public class DirectReceiver {

    private final Logger logger = LoggerFactory.getLogger(getClass());


    /***
     * 自动创建队列 directQueue1 ,并关联死信队列
     * Exchange（默认direct） 与 Queue绑定
     * 指定 routing key
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "directQueue1",
                    arguments = {@Argument(name = "x-dead-letter-exchange",value = RmqConst.dead_letter_exchange),
                            @Argument(name = "x-dead-letter-routing-key",value = RmqConst.dead_letter_routing_key)}),
            key = "user.info",
            exchange = @Exchange("myDirectExChange")
    ))
    public void directQueue1(Message message, Channel channel) throws Exception {
        logger.info("directQueue1-user.info: {}", message);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        //channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);

    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("directQueue2"),
            key = "user.work",
            exchange = @Exchange(value = "myDirectExChange",type = ExchangeTypes.DIRECT)
    ))
    public void directQueue2(Message message, Channel channel) throws IOException {
        logger.info("directQueue2-user.work: {}", message);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
